using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine.UI;
using TMPro;

public class WorldRank : MonoBehaviour
{
    // 排行榜类型枚举
    public enum RankType
    {
        Score,      // 积分排行
        WinStreak,  // 连胜排行
        Level,       // 段位排行
        AnsNum        // 答题排行
    }

    [Header("UI References")]
    [SerializeField] private Toggle scoreRankToggle;      // 积分排行切换
    [SerializeField] private Toggle winStreakToggle;      // 连胜排行切换
    [SerializeField] private Toggle levelRankToggle;      // 段位排行切换
    [SerializeField] private Toggle ansNumRankToggle;     // 答题排行切换
    [SerializeField] private ScrollRect scrollRect;       // 滑动组件
    [SerializeField] private Transform rankListContent;   // 排行榜列表容器
    [SerializeField] private GameObject rankItemPrefab;   // 排行榜项预制体

    // 排行榜数据结构
    [Serializable]
    public class RankData
    {
        public int id;                          // 用户ID
        public string name;                     // 用户名称
        public string avatar_url;               // 头像URL
        public int score;                       // 分数
        public int level;                       // 等级
        public int liansheng;                   // 连胜次数
        public int success_nums;                // 成功次数
        public int total_nums;                  // 总次数
        public string score_last_update_time;   // 最后更新时间
    }

    [Serializable]
    public class RankResponse
    {
        public int status;                      // 状态码
        public List<RankData> data;             // 排行榜数据
    }

    private const string BASE_URL = "https://api.question.game.xmnk.cn/";
    private RankType currentRankType = RankType.Score;
    private const int DEFAULT_PAGE_SIZE = 15;
    private int currentPage = 1;
    private bool isLoading = false;
    private float scrollThreshold = 0.8f; // 滑动阈值，超过这个值就加载下一页
    private bool hasMoreData = true; // 是否还有更多数据

    private static readonly string[] LevelNames = { "幼儿园", "小学生", "初中生", "高中生" ,"大学生","博士生"};

    private void Start()
    {
        InitializeUI();
        GetDefaultRank();
    }

    private void InitializeUI()
    {
        // 绑定Toggle事件
        scoreRankToggle.onValueChanged.AddListener((isOn) => OnRankTypeToggleChanged(RankType.Score, isOn));
        winStreakToggle.onValueChanged.AddListener((isOn) => OnRankTypeToggleChanged(RankType.WinStreak, isOn));
        levelRankToggle.onValueChanged.AddListener((isOn) => OnRankTypeToggleChanged(RankType.Level, isOn));
        ansNumRankToggle.onValueChanged.AddListener((isOn) => OnRankTypeToggleChanged(RankType.AnsNum, isOn));

        // 添加滑动监听
        scrollRect.onValueChanged.AddListener(OnScrollValueChanged);

        // 设置默认选中状态
        scoreRankToggle.isOn = true;
    }

    private void OnRankTypeToggleChanged(RankType type, bool isOn)
    {
        if (!isOn) return; // 只处理选中事件

        if (currentRankType == type) return;

        currentRankType = type;
        currentPage = 1;
        UpdateRankTypeUI();
        ClearRankList();
        LoadRankList();
        hasMoreData = true; // 每次切换榜单或刷新时，重置 hasMoreData
    }

    private void UpdateRankTypeUI()
    {
        // 更新Toggle状态
        scoreRankToggle.isOn = currentRankType == RankType.Score;
        winStreakToggle.isOn = currentRankType == RankType.WinStreak;
        levelRankToggle.isOn = currentRankType == RankType.Level;
        ansNumRankToggle.isOn = currentRankType == RankType.AnsNum;
    }

    private void OnScrollValueChanged(Vector2 value)
    {
        if (!isLoading && hasMoreData && value.y <= 0.05f)
        {
            LoadNextPage();
        }
    }

    private void LoadRankList()
    {
        isLoading = true;
        GetRankList(currentRankType, currentPage, DEFAULT_PAGE_SIZE, OnRankListReceived);
    }

    private void LoadNextPage()
    {
        if (!isLoading && hasMoreData)
        {
            currentPage++;
            LoadRankList();
        }
    }

    private void ClearRankList()
    {
        foreach (Transform child in rankListContent)
        {
            Destroy(child.gameObject);
        }
    }

    private void OnRankListReceived(RankResponse response)
    {
        isLoading = false;
        if (response != null && response.status == 0 && response.data != null)
        {
            Debug.Log("收到数据条数: " + response.data.Count);
            UpdateRankListUI(response.data);

            // 判断是否还有更多数据
            if (response.data.Count < DEFAULT_PAGE_SIZE)
            {
                hasMoreData = false; // 没有更多数据了
            }
            else
            {
                hasMoreData = true; // 还有下一页
            }
        }
        else
        {
            Debug.LogError("获取排行榜数据失败, response is null: " + (response == null));
            // hasMoreData = false; // 请求失败也不再请求
        }
    }

    private void UpdateRankListUI(List<RankData> rankDataList)
    {
        // 创建新的列表项
        foreach (var rankData in rankDataList)
        {
            GameObject rankItem = Instantiate(rankItemPrefab, rankListContent);
            UpdateRankItemUI(rankItem, rankData);
        }
    }

    private void UpdateRankItemUI(GameObject rankItem, RankData rankData)
    {
        // 排名
        var rankText = rankItem.transform.Find("rank/Text").GetComponent<UnityEngine.UI.Text>();
        rankText.text = (rankListContent.childCount).ToString();

        // 头像
        var avatarImage = rankItem.transform.Find("user/Avatar").GetComponent<UnityEngine.UI.Image>();
        ImageLoader.Instance.LoadImageFromUrl(avatarImage, rankData.avatar_url);

        // 昵称
        var nickText = rankItem.transform.Find("user/Nick").GetComponent<UnityEngine.UI.Text>();
        nickText.text = rankData.name;

        // 连胜
        var lianshengText = rankItem.transform.Find("Liansheng/Text").GetComponent<UnityEngine.UI.Text>();
        lianshengText.text = rankData.liansheng.ToString();

        // 段位（映射）
        var duanweiText = rankItem.transform.Find("Duanwei/Text").GetComponent<UnityEngine.UI.Text>();
        if (rankData.level >= 0 && rankData.level < LevelNames.Length)
            duanweiText.text = LevelNames[rankData.level];
        else
            duanweiText.text = "未知";

        // 答题
        var datiText = rankItem.transform.Find("Dati/Text").GetComponent<UnityEngine.UI.Text>();
        datiText.text = $"{rankData.total_nums}";

        // 积分
        var jifenText = rankItem.transform.Find("Jifen/Text").GetComponent<UnityEngine.UI.Text>();
        jifenText.text = rankData.score.ToString();
    }

    // 获取排行榜数据
    public async void GetRankList(RankType type, int page = 1, int pageSize = DEFAULT_PAGE_SIZE, Action<RankResponse> callback = null)
    {
        Debug.Log("GetRankList");
        currentRankType = type;
        string endpoint = GetEndpointByType(type);
        await FetchRankData(endpoint, page, pageSize, callback);
    }

    // 根据类型获取对应的接口地址
    private string GetEndpointByType(RankType type)
    {
        switch (type)
        {
            case RankType.Score:
                return "gameUser/scoreRanking";
            case RankType.WinStreak:
                return "gameUser/lianshengRanking";
            case RankType.Level:
                return "gameUser/levelRanking";
            case RankType.AnsNum:
                return "gameUser/questionRanking";
            default:
                return "gameUser/scoreRanking";
        }
    }

    // 获取默认排行榜（积分排行）
    public void GetDefaultRank()
    {
        GetRankList(currentRankType, currentPage, DEFAULT_PAGE_SIZE, OnRankListReceived);
    }

    // 发送网络请求获取排行榜数据
    private async Task FetchRankData(string endpoint, int page, int pageSize, Action<RankResponse> callback)
    {
        RankResponse rankResponse = null;
        try
        {
            var response = await HttpClientService.Instance
                .Get(endpoint)
                .AddQueryParam("page", page.ToString())
                .AddQueryParam("pre_page", pageSize.ToString())
                .SendAsync();

            if (response.IsSuccess)
            {
                try
                {
                    if (string.IsNullOrEmpty(response.Content))
                    {
                        Debug.LogError("FetchRankData: response.Content is null or empty!");
                    }
                    else
                    {
                        rankResponse = JsonUtility.FromJson<RankResponse>(response.Content);
                        Debug.Log($"FetchRankData: 反序列化成功, status={rankResponse?.status}, data count={rankResponse?.data?.Count ?? -1}");
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"FetchRankData: 反序列化异常: {ex.Message}");
                    Debug.LogError($"FetchRankData: 原始内容: {response.Content}");
                }
            }
            else
            {
                Debug.LogError($"FetchRankData: 网络请求失败: {response.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"FetchRankData: 网络异常: {ex.Message}");
        }

        // 只在最后统一回调
        callback?.Invoke(rankResponse);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
